<template>
  <div class="tw-formlist-upload">
    <el-upload
      class="tw-upload-data"
      ref="libupload"
      :action="action"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="handleBeforeRemove"
      :multiple="multiple"
      :headers="headers"
      :on-change="handleChange"
      :limit="limit"
      :on-progress="handleProgress"
      :on-success="handleSuccess"
      :on-error="handleError"
      :before-upload="handleBeforeUpload"
      :list-type="listtype"
      :auto-upload="autoupload"
      :data="data"
      :drag="drag"
      :disabled="disabled || (limit > 0 && fileList.length >= limit)"
      :accept="accept"
      :with-credentials="withcredentials"
      :on-exceed="handleExceed"
      :show-file-list="showfilelist"
      :file-list="fileList">
      <el-button :size="size" :type="btnType" v-html="placeholder" :disabled="disabled || (limit > 0 && fileList.length >= limit)"></el-button>
      <div slot="tip" class="el-upload__tip" v-html="tips"></div>
    </el-upload>
    <ul class="el-upload-list el-upload-list--text" v-if="useCustFilelist">
      <li tabindex="0" class="el-upload-list__item is-success" v-for="(file,idx) in fileList" :key="idx">
        <a class="el-upload-list__item-name" @click="handlePreview(file, idx)">
          <template v-if="useCustFileicon">
            <i v-if="file.iconCss && file.iconCss !==''" class="tw-ico" :class="file.iconCss"></i>
            <template v-else-if="icons.length>0">
              <img v-if="icons[1] && icons[1] !== '' && file.format && ['jpg', 'jpeg', 'gif', 'png', 'bmp'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[1].localPath}`" />
              <img v-else-if="icons[2] && icons[2] !== '' && file.format && ['doc', 'docx', 'wps'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[2].localPath}`" />
              <img v-else-if="icons[3] && icons[3] !== '' && file.format && ['xls', 'xlsx'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[3].localPath}`" />
              <img v-else-if="icons[4] && icons[4] !== '' && file.format && ['ppt', 'pptx'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[4].localPath}`" />
              <img v-else-if="icons[5] && icons[5] !== '' && file.format && ['pdf'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[5].localPath}`" />
              <img v-else-if="icons[6] && icons[6] !== '' && file.format && ['txt'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[6].localPath}`" />
              <img v-else-if="icons[7] && icons[7] !== '' && file.format && ['zip', 'rar', '7z'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[7].localPath}`" />
              <img v-else-if="icons[8] && icons[8] !== '' && file.format && ['mp4', 'avi', 'mpg', 'm3u8', 'mpeg', 'flv'].includes(file.format)" class="xicon" :src="`${$twApp.fileBaseUrl}${icons[8].localPath}`" />
              <img v-else class="xicon" :src="`${$twApp.fileBaseUrl}${icons[0].localPath}`" />
            </template>
          </template>
          <i class="el-icon-document" v-else></i>
          {{file.fileName}}
        </a>
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-circle-check"></i>
        </label>
        <i class="el-icon-close"  @click="handleRemove(file, idx)"></i>
        <el-progress
          v-if="file.status === 'uploading'"
          type="line"
          :stroke-width="2"
          :percentage="parseInt(file.percentage)">
        </el-progress>
      </li>
    </ul>
  </div>
</template>

<script>
// import props from './props'

export default {
  name: 'libinput',

  inject: ['_root'],

  props: {
    value: {
      type: Array,
      default: () => []
    },
    action: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: 'small'
    },
    limit: {
      type: String,
      default: ''
    },
    maxsize: {
      type: String,
      default: '2M'
    },

    multiple: {
      type: Boolean,
      default: false
    },

    drag: {
      type: String,
      default: false
    },
    disabled: {
      type: String,
      default: false
    },

    autoupload: {
      type: Boolean,
      default: true
    },

    listtype: {
      type: String,
      default: 'text'
    },

    placeholder: {
      type: String,
      default: '<span style="padding: 0px 20px;"><i class="el-icon-plus"></i> 文件上传</span>'
    },
    accept: {
      type: String,
      default: ''
    },

    showfilelist: {
      type: Boolean,
      default: false
    },
    withcredentials: {
      type: Boolean,
      default: false
    },

    tips: {
      type: String,
      default: '<div style=\"width:100%;text-align:left;\">温馨提示：上传要求：支持.docx .doc .wps .pdf .txt,.xlsx .xls .et .jpg .jpeg .bmp .png .gif .swf .rar .zip格式文件； 文件大小不超过5M。</div>'
    },
    useCustFilelist: {
      type: Boolean,
      default: true
    },
    useCustFileicon: {
      type: Boolean,
      default: true
    },
    icons: {
      type: Array,
      default: () => []
    },

    value: {
      type: Array,
      default: () => []
    },
    btnType: {
      type: String,
      default: 'success'
    },
    closeAlert: {
      type: Boolean,
      default: false
    },
  },

  data () {
    return {
      fileList: []
    }
  },

  methods: {
    handleRemove (file, idx) {
      if (this.disabled) {
        return
      }
      if (!this.validBeforeUpload(file, false)) {
        return
      }
      if (this._root.onRemove !== '' &&  typeof this._root.onRemove === 'function') {
        this._root.onRemove(file, idx, this)
      } else {
        let that = this
        if (this.closeAlert) {
          that.fileList.splice(idx, 1)
          window.$ui.msg.success("删除成功")
        } else {
          window.$ui.confirm('是否删除此附件？','提示',{
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.fileList.splice(idx, 1)
            window.$ui.msg.success("删除成功")
          })
        }
      }
    },
    handlePreview (file, idx) {
      if (this._root.onPreview !== '' &&  typeof this._root.onPreview === 'function') {
        this._root.onPreview(file, idx, this)
      } else {
        this._root.$emit('selectfile', file)
      }
    },
    handleExceed (files, fileList) {
      if (this._root.onExceed !== '' &&  typeof this._root.onExceed === 'function') {
        this._root.onExceed(files, fileList, this)
      } else {
        window.$ui.msg.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      }
    },
    handleBeforeRemove (file, fileList) {
      if (this._root.beforeRemove !== '' &&  typeof this._root.beforeRemove === 'function') {
        this._root.beforeRemove(file, fileList, this)
      }
    },
    handleBeforeUpload (file) {
      return this.validBeforeUpload(file)

      // const isJPG = file.type === 'image/jpeg';
      // const isPNG = file.type === 'image/png';
      // const isPG = (isJPG || isPNG)                                       //限制图片格式为jpg / png
      // const isLt2M = file.size / 1024 / 1024 < 2;                         //限制图片大小
      // const isSize = new Promise(function(resolve,reject) {
      //     let width = 600
      //     let height = 400
      //     let _URL = window.URL || window.webkitURL
      //     let img = new Image()
      //     img.onload = function() {
      //         let valid = img.width >= width && img.height >= height
      //         valid ? resolve() : reject();
      //     }
      //     img.src = _URL.createObjectURL(file)
      // }).then(() => {
      //     return file;
      // },()=>{
      //     this.$message.error('上传图片像素要大于600*400!');
      //     return promise.reject();
      // })
      // if (!isPG) {
      //     this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      // }
      // if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      //   return isPG && isLt2M && isSize
      // }
    },
    validBeforeUpload (file, showmsg = true) {
      if (this._root.beforeUpload !== '' &&  typeof this._root.beforeUpload === 'function') {
        return this._root.beforeUpload(file, this)
      } else {
        if (this.maxsize && this.maxsize.toUpperCase().indexOf('M') > -1) {
          if (file.size / 1024 / 1024 > parseFloat(this.maxsize)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件大小不能超过 ${this.maxsize} `)
            }
            return false
          }
        } else if (this.maxsize && this.maxsize.toUpperCase().indexOf('K') > -1) {
          if (file.size / 1024 > parseFloat(this.maxsize)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件大小不能超过 ${this.maxsize} `)
            }
            return false
          }
        }

        if (this.accept && file && file.name) {
          let filearr = file.name.split('.')
          let filetype = ''
          if (filearr.length > 0) {
            filetype = filearr[filearr.length - 1].toLowerCase()
          }
          if (filetype && !this.accept.split(', ').includes(filetype)) {
            if (showmsg) {
              window.$ui.msg.warning(`上传文件格式限制为：${this.accept} `)
            }
            return false
          }

          // docx .doc .wps .pdf .txt,.xlsx .xls .et .jpg .jpeg .bmp .png .gif .swf .rar .zip
        }

        return true
      }
    },
    handleError (err, file, fileList) {
      if (this._root.onError !== '' &&  typeof this._root.onError === 'function') {
        this._root.onError(err, file, fileList, this)
      }
    },
    // handleHttpRequest () {

    // },
    handleSuccess(response, file, fileList) {
      if (this._root.onSuccess !== '' && typeof this._root.onSuccess === 'function') {
        this._root.onSuccess(response, file, fileList, this)
      }
    },
    handleProgress(event, file, fileList) {
      if (this._root.onProgress !== '' &&  typeof this._root.onProgress === 'function') {
        this._root.onProgress(event, file, fileList, this)
      }
    },
    handleChange (files, fileList) {
      if (this._root.onChange !== '' &&  typeof this._root.onChange === 'function') {
        this._root.onChange(files, fileList, this)
      } else {
        if (!this.validBeforeUpload(files, false)) {
          return
        }
        let filearr = []
        fileList.forEach((itm) => {
          if (itm.response && itm.response.fileInfos) {
            filearr.push({
              ...itm.response.fileInfos[0]
            })
          } else {
            filearr.push({...itm})
          }
        })
        this.fileList = filearr
        this.$emit('input', filearr)
        this.$emit('change', filearr)
      }
    }
  },

  computed: {
    headers () {
      let r = {}
      let branchCode = this.$twApp.user.branchCode || 'CXY0001'
      r = { branchCode: branchCode, 'Access-Token': this.$twApp.user.token, 'Current-Org-Id': this.$twApp.user.orgId }
      return r
    },
    data () {
      return null
    }
  },

  mounted () {
    this.fileList = this.value
  },

  watch: {
    value: {
      deep: true,
      handler () {
        this.fileList = this.value
      }
    }
  }
}
</script>
